/*
 * Copyright 2011 ArcBees Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.arcbees.server.auth;

import java.util.List;

import com.google.inject.Inject;

/**
 * @author Christian Goudreau
 */
public class UserDao extends DaoImpl<User> {
  @Inject
  UserDao(final Datastore datastore) {
    super(User.class, datastore);
  }

  public Boolean authenticate(UserDto userToAuthenticate) {
    User user = getDatastore().load(User.class, userToAuthenticate.getEmail());

    if (user != null
        && BCrypt.checkpw(userToAuthenticate.getPassword(), user.getHash())) {
      return true;
    }

    return false;
  }

  public boolean register(UserDto userDto) {
    String hash = BCrypt.hashpw(userDto.getPassword(), BCrypt.gensalt());

    User user = new User(userDto.getEmail(), hash);

    return getDatastore().store(user);
  }

  public UserDto loadUserDto(String key) {
    User user = load(key);

    UserDto userDto = new UserDto();
    userDto.setEmail(user.getEmail());
    userDto.setLogged(true);
    userDto.setSearchProfileIds(user.getSearchProfileIds());
    
    return userDto;
  }

  public void associateSearchProfileIdToUser(UserDto currentUser, String searchProfileId) {
    User user = getDatastore().load(User.class, currentUser.getEmail());
    List<String> userSearchprofileIds = user.getSearchProfileIds();
    
    if (!userSearchprofileIds.contains(searchProfileId)) {
      userSearchprofileIds.add(searchProfileId);
    }
    
    currentUser.setSearchProfileIds(userSearchprofileIds);
  }
  
  public void put(UserDto userDto){
    User user = getDatastore().load(User.class, userDto.getEmail());
    
    user.setSearchProfileIds(userDto.getSearchProfileIds());
    
    getDatastore().put(user);
  }
}
